import cProfile, pstats 
import sys, os, time, glob
import inspect
import distutils.debug

def IsPydevDebugMode():
    # Get the first file of the stack
    scriptpath=inspect.stack().pop()[1]    
    return os.path.basename(scriptpath)=="pydevd.py"

def GenerateReport(infile, outfile):
    # Generate the report
    outstream=file(outfile,"w")
    stat=pstats.Stats(infile,stream=outstream)
    stat.strip_dirs( ) 
    stat.sort_stats('t')
    stat.print_stats(.1 )

#avoid the debugger interferences
if IsPydevDebugMode():
    print "Profiling can't stand debugger overhead"
    sys.exit(1)
    

# Find the first free prefix
filelist=glob.glob("profile-*.profile")
for x in range(1,1000):
    prefix="profile-%3.3d"%x
    if not prefix+".profile" in filelist:
        break
    
# Print a debug message
sys.stderr.write("Profile application performances\n")
sys.stderr.write("log data to '%s'\n\n"%prefix)
time.sleep(1)

# Hot shot
os.environ["profiling"]="200"
cProfile.run("execfile('borgwar.py')",prefix+".profile")

# Generate last date
infilelist=glob.glob("profile-*.profile")
infilelist.sort()
infilelist=infilelist[-2:]
outfilelist=[]
for infile in infilelist:
    outfile= os.path.splitext(infile)[0]+".log"
    outfilelist.append(outfile)
    GenerateReport(infile, outfile)

if len(outfilelist)>1:
    os.environ['path']+=r";D:\Program Files\WinMerge"
    os.environ['path']+=r";C:\Program Files\WinMerge"
    winmerge=r"WinMergeU.exe"
    print '"%s" "%s" "%s"'%(winmerge,
                            outfilelist[0],
                            outfilelist[1])
    os.system('%s /e "%s" "%s"'%(winmerge,outfilelist[0],outfilelist[1]))
else:
    os.system('notepad "%s"'%outfilelist[0])



